"""
Support module for logAnalyzer.py to get IP's Location.

This module uses the GEOIP database to determin the ip location.
"""

import pygeoip 

class getLocation:
	"""
	Gets the location of a given IP. It can output IP Country
	or IP Country and City details.
	
	Keyword arguments:
    ip -- IP to search location for
	"""

	def __init__(self, ip):
		"""Default Constructor"""
		self.ip = ip
		
	def __str__(self):
		"""Default String Output"""
		return ""
					
	def getCountry(self):
		"""Returns the IP's Country if it's in the database. If not, returns Unknown"""
		countryDatabase = pygeoip.GeoIP('database/GeoIP.dat', pygeoip.MEMORY_CACHE)
		try:
			x = countryDatabase.country_name_by_addr(self.ip)
		except:
			x = 'Unknown'
		return x
		
	def getCity(self):
		"""Returns the IP's City if it's in the database. If not, returns Unknown with 0 lat. and long."""
		cityDatabase = pygeoip.GeoIP('database/GeoLiteCity.dat', pygeoip.MEMORY_CACHE)
		try:
			gir = cityDatabase.record_by_addr(self.ip)
			return { 'city':gir['city'], 'log':gir['longitude'], 'lat':gir['latitude'] }
		except:
			return { 'city':'unknown', 'log':0, 'lat':0 }
